<?php
/**
 *+------------------
 * Ingenious
 *+------------------
 * Copyright (c) https://gitee.com/ingenstream/ingenious  All rights reserved.
 *+------------------
 * Author: Mr. April (405784684@qq.com)
 *+------------------
 * Software Registration Number: 2024SR0694589
 * Official Website: http://www.ingenstream.cn
 */

namespace madong\think\wf\model;

use madong\think\wf\basic\BaseModel;
use madong\ingenious\interface\model\IProcessForm;

/**
 * 流程定义-模型
 *
 * @author Mr.April
 * @since  1.0
 */
class ProcessForm extends BaseModel implements IProcessForm
{

    /**
     * 数据表主键
     *
     * @var string
     */
    protected $pk = 'id';

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'wf_process_form';


    /**
     * 是否指定时间戳
     *
     * @var bool
     */
    public $autoWriteTimestamp = true;


    protected $append = ['type_name', 'create_date', 'update_date'];


    /**
     * 定义访问器
     *
     * @return null
     */
    public function getTypeNameAttr(): mixed
    {
        return $this->types ? $this->types->name : null;
    }

    public function searchIdAttr($query, $value)
    {
        if ($value) {
            $query->where('id', $value);
        }
    }

    public function searchTypeIdAttr($query, $value)
    {
        if (!empty($value)) {
            $query->where('type_id', $value);
        }
    }

    public function searchNotIdAttr($query, $value)
    {
        if ($value) {
            $query->where('id', '<>', $value);
        }
    }

    /**
     * 唯一编码
     *
     * @param $query
     * @param $value
     */
    public function searchNameAttr($query, $value)
    {
        if ($value) {
            $query->where('name', $value);
        }
    }

    /**
     * 显示名称搜索器
     *
     * @param $query
     * @param $value
     */
    public function searchDisplayNameAttr($query, $value)
    {
        if ($value) {
            $query->whereLike('display_name', '%' . $value . '%');
        }
    }

    /**
     * 流程定义描述搜索器
     *
     * @param $query
     * @param $value +
     */
    public function searchDescriptionAttr($query, $value)
    {
        if ($value) {
            $query->whereLike('description', '%' . $value . '%');
        }
    }

    /**
     * 定义管理一对一流程类型表
     *
     * @return HasOne
     */
    public function types()
    {
        return $this->hasOne(ProcessType::class, 'id', 'type_id')->where('enabled', 1);
    }

    /**
     * 定义关联一对多历史表
     *
     * @return HasMany
     */
    public function history()
    {
        return $this->hasMany(ProcessFormHistory::class, 'process_form_id', 'id');
    }

    /**
     * 删除设计及其关联的历史记录
     *
     * @return bool
     */
    public function deleteWithHistory(): bool
    {
        $this->history()->delete();
        return $this->delete();
    }

}
